<template>
  <el-dialog
    title="创建跟单"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="orderData" class="order-info-section">
      <h4 style="margin: 0 0 15px 0; color: #303133;">订单信息</h4>
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="订单编号">
          <span style="color: #409EFF; font-weight: bold;">{{ orderData.order_no }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单名称">{{ orderData.name }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">
          {{ orderData.currency }}{{ orderData.order_amount }}
        </el-descriptions-item>
        <el-descriptions-item label="交货日期">{{ orderData.ending_date }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 已有跟单列表 -->
    <div v-if="existingPurchasesLoading || existingPurchases.length > 0" class="existing-purchases-section">
      <h4 style="margin: 0 0 15px 0; color: #E6A23C; display: flex; align-items: center;">
        <i class="el-icon-warning" style="margin-right: 5px;" />
        <span v-if="existingPurchasesLoading">正在加载跟单记录...</span>
        <span v-else>该订单已有跟单记录 ({{ existingPurchases.length }}条)</span>
      </h4>
      <div v-if="existingPurchasesLoading" style="text-align: center; padding: 20px;">
        <i class="el-icon-loading" style="font-size: 20px; color: #409EFF;" />
        <p style="margin-top: 10px; color: #909399;">正在加载已有跟单记录...</p>
      </div>
      <el-table v-else :data="existingPurchases" size="small" border>
        <el-table-column label="供应商" width="140">
          <template slot-scope="scope">
            <span style="font-weight: bold; color: #E6A23C;">{{ scope.row.crmsupplier_data.name }}</span>
            <div v-if="scope.row.crmsupplier_data.wechatgroup" style="font-size: 11px; color: #909399; margin-top: 2px;">
              <i class="el-icon-chat-dot-round" style="color: #67C23A;" />
              {{ scope.row.crmsupplier_data.wechatgroup }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 'pending' ? 'warning' : (scope.row.status === 'open' ? 'primary' : (scope.row.status === 'completed' ? 'success' : 'danger'))"
              size="mini"
            >
              {{ scope.row.status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最新进展" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="font-size: 12px;">{{ scope.row.progress || '暂无进展' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="跟进人" width="80">
          <template slot-scope="scope">
            <span style="font-size: 12px;">{{ scope.row.creator_name }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!existingPurchasesLoading && existingPurchases.length > 0" style="margin-top: 10px; padding: 8px; background-color: #fff6f7; border: 1px solid #fbc4c4; border-radius: 4px; font-size: 12px; color: #f56c6c;">
        <i class="el-icon-info" />
        <strong>建议：</strong>请检查上述跟单记录，避免重复创建相同供应商的跟单。如确需创建新跟单，请选择不同的供应商。
      </div>
    </div>

    <el-divider />

    <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item label="选择供应商" prop="crmsupplier_id">
        <el-select
          v-model="form.crmsupplier_id"
          placeholder="请输入关键词搜索供应商"
          style="width: 100%;"
          filterable
          remote
          reserve-keyword
          :remote-method="searchSuppliers"
          :loading="supplierSearchLoading"
          clearable
          @change="checkDuplicateSupplier"
        >
          <el-option
            v-for="supplier in supplierOptions"
            :key="supplier.id"
            :label="supplier.name"
            :value="supplier.id"
            :disabled="isDuplicateSupplier(supplier.id)"
          >
            <span style="float: left;">
              {{ supplier.name }}
              <el-tag v-if="isDuplicateSupplier(supplier.id)" type="warning" size="mini" style="margin-left: 8px;">
                已存在
              </el-tag>
            </span>
            <span style="float: right; color: #8492a6; font-size: 13px;">
              {{ supplier.contact_name }}
              <span v-if="supplier.wechatgroup" style="margin-left: 8px;">
                <i class="el-icon-chat-dot-round" style="color: #67C23A;" />
                {{ supplier.wechatgroup }}
              </span>
            </span>
          </el-option>
        </el-select>
        <div style="font-size: 12px; color: #909399; margin-top: 5px;">
          <i class="el-icon-info" /> 输入供应商名称、联系人或微信群名进行搜索
        </div>
        <!-- 重复供应商警告 -->
        <div v-if="duplicateWarning" style="margin-top: 8px; padding: 6px 10px; background-color: #fdf6ec; border: 1px solid #f5dab1; border-radius: 4px; font-size: 12px; color: #e6a23c;">
          <i class="el-icon-warning" />
          <strong>警告：</strong>{{ duplicateWarning }}
        </div>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
          <el-option label="开启" value="open" />
          <el-option label="完成" value="completed" />
          <el-option label="取消" value="cancelled" />
        </el-select>
      </el-form-item>

      <el-form-item label="初始进展" prop="progress">
        <el-input
          v-model="form.progress"
          type="textarea"
          :rows="3"
          placeholder="请输入当前采购进展情况（可选）"
        />
      </el-form-item>

      <el-form-item label="初始备注" prop="initial_remark">
        <el-input
          v-model="form.initial_remark"
          type="textarea"
          :rows="3"
          placeholder="请输入初始备注（可选）"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">创建跟单</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as crmorderpurchase from '@/api/crm/crmorderpurchase'

/**
 * 跟单创建组件
 *
 * 功能特点：
 * - 显示订单基本信息
 * - 支持供应商搜索选择（按名称、联系人、微信群名搜索）
 * - 支持设置初始状态、进展和备注
 * - 独立组件，便于复用
 *
 * 使用方法：
 * <CRMAddOrderPurchase
 *   :visible="visible"
 *   :order-data="orderData"
 *   @close="visible = false"
 *   @success="handleSuccess"
 * />
 */
export default {
  name: 'CRMAddOrderPurchase',
  props: {
    // 对话框显示状态
    visible: {
      type: Boolean,
      default: false
    },
    // 订单数据
    orderData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      submitLoading: false,

      // 表单数据
      form: {
        crmorder_id: '',
        crmsupplier_id: '',
        status: 'open',
        progress: '',
        initial_remark: ''
      },

      // 表单验证规则
      rules: {
        crmsupplier_id: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },

      // 供应商搜索
      supplierOptions: [],
      supplierSearchLoading: false,
      supplierSearchTimer: null,

      // 已有跟单列表
      existingPurchases: [],
      existingPurchasesLoading: false,

      // 重复供应商警告
      duplicateWarning: ''
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.resetForm()
        if (this.orderData && this.orderData.id) {
          this.form.crmorder_id = this.orderData.id
          // 获取该订单已有的跟单记录
          this.getExistingPurchases()
        }
      }
    },
    dialogVisible(val) {
      if (!val) {
        this.$emit('close')
      }
    }
  },
  beforeDestroy() {
    // 清理计时器
    if (this.supplierSearchTimer) {
      clearTimeout(this.supplierSearchTimer)
    }
  },
  methods: {
    /**
     * 重置表单
     */
    resetForm() {
      this.form = {
        crmorder_id: this.orderData?.id || '',
        crmsupplier_id: '',
        status: 'open',
        progress: '',
        initial_remark: ''
      }
      this.supplierOptions = []
      this.existingPurchases = []
      this.duplicateWarning = ''
      // 清除表单验证
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },

    /**
     * 获取该订单已有的跟单记录
     */
    getExistingPurchases() {
      if (!this.orderData || !this.orderData.id) {
        return
      }

      this.existingPurchasesLoading = true
      const params = new URLSearchParams()
      params.append('order_id', this.orderData.id)
      params.append('pageSize', '50') // 获取前50条记录

      crmorderpurchase.Get(params.toString()).then(response => {
        if (response.success) {
          this.existingPurchases = response.data.data || []
          console.log('已有跟单记录:', this.existingPurchases)
        } else {
          console.error('获取已有跟单失败:', response.msg)
          this.existingPurchases = []
        }
      }).catch(error => {
        console.error('获取已有跟单失败:', error)
        this.existingPurchases = []
      }).finally(() => {
        this.existingPurchasesLoading = false
      })
    },

    /**
     * 搜索供应商
     * @param {string} query - 搜索关键词
     */
    searchSuppliers(query) {
      if (!query || query.trim() === '') {
        this.supplierOptions = []
        return
      }

      // 防抖处理
      clearTimeout(this.supplierSearchTimer)
      this.supplierSearchTimer = setTimeout(() => {
        this.supplierSearchLoading = true
        crmorderpurchase.SearchSuppliers(query.trim()).then(response => {
          if (response.success) {
            this.supplierOptions = response.data || []
          } else {
            this.$message.error(response.msg || '搜索供应商失败')
            this.supplierOptions = []
          }
        }).catch(() => {
          this.$message.error('搜索供应商失败')
          this.supplierOptions = []
        }).finally(() => {
          this.supplierSearchLoading = false
        })
      }, 300) // 300ms防抖
    },

    /**
     * 提交表单
     */
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          crmorderpurchase.Post(this.form).then(response => {
            if (response.success) {
              this.$message.success('跟单创建成功')
              this.$emit('success', response.data)
              this.handleClose()
            } else {
              this.$message.error(response.msg || '创建跟单失败')
            }
          }).catch(() => {
            this.$message.error('创建跟单失败')
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    },

    /**
     * 关闭对话框
     */
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },

    /**
     * 检查是否为重复供应商
     * @param {number} supplierId - 供应商ID
     * @returns {boolean} 是否重复
     */
    isDuplicateSupplier(supplierId) {
      return this.existingPurchases.some(purchase =>
        purchase.crmsupplier_data.id === supplierId
      )
    },

    /**
     * 检查重复供应商并显示警告
     */
    checkDuplicateSupplier() {
      this.duplicateWarning = ''

      if (!this.form.crmsupplier_id) {
        return
      }

      const existingPurchase = this.existingPurchases.find(purchase =>
        purchase.crmsupplier_data.id === this.form.crmsupplier_id
      )

      if (existingPurchase) {
        const supplierName = existingPurchase.crmsupplier_data.name
        const status = existingPurchase.status_display
        const creator = existingPurchase.creator_name

        this.duplicateWarning = `该订单已存在供应商"${supplierName}"的跟单记录（状态：${status}，跟进人：${creator}），请确认是否需要创建新的跟单。`
      }
    }
  }
}
</script>

<style scoped>
.order-info-section {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
}

.existing-purchases-section {
  background-color: #fef9e7;
  border: 1px solid #f7d794;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
}

.existing-purchases-section .el-table {
  background-color: transparent;
}

.existing-purchases-section .el-table th {
  background-color: #fdeaa7;
}

.dialog-footer {
  text-align: right;
}

/* 供应商选项样式优化 */
.el-select-dropdown__item {
  height: auto;
  line-height: 1.4;
  padding: 8px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-info-section {
    padding: 10px;
  }
}
</style>
